package com.dxyxx.framework;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;
import org.json.JSONException;
import org.json.JSONObject;

import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;
import zrc.widget.ZrcListView.OnStartListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.pierry.simpletoast.SimpleToast;

import com.android.customized.ExpandView;
import com.android.customized.PullDownView;
import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.framework.CAS.CallBack;
import com.dxyxx.framework.CategoryFragment.GridAdapter;
import com.dxyxx.framework.CategoryFragment.PageChangeListener;
import com.dxyxx.pojo.Category;
import com.dxyxx.pojo.Comment;
import com.dxyxx.pojo.CommentRecords;
import com.dxyxx.pojo.CommentReply;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.utils.RelativeDateFormat;
import com.dynamic.WriteActivity;
import com.gghl.view.wheelview.MyAlertDialog;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ta.utdid2.android.utils.StringUtils;
import com.weixinninegridlayout.CustomImageView;
import com.weixinninegridlayout.Image;
import com.weixinninegridlayout.NineGridlayout;
import com.weixinninegridlayout.ScreenTools;

public class CommentFragment extends BaseFragment {
	private final static String FROM = "from";
	private final static String TIME = "time";
	private final static String IMAGE = "image";
	private final static String WORD = "word";
	private final static String ID = "id";
	private final static String REPLYS = "replys";
	private final static String CID = "cid";
	private final static String THUMB = "thumb";
	private final static String USERNAME = "userName";
	private final static int COUNT = 5;
	private String phone;

	private ArrayList<String> msgs;
	private int pageId = -1;
	private MyAdapter2 adapter;

	//	private static final String[][] names = new String[][] { { "加拿大", "瑞典", "澳大利亚", "瑞士", "新西兰", "挪威", "丹麦", "芬兰", "奥地利", "荷兰", "德国", "日本", "比利时", "意大利", "英国" }, { "德国", "西班牙", "爱尔兰", "法国", "葡萄牙", "新加坡", "希腊", "巴西", "美国", "阿根廷", "波兰", "印度", "秘鲁", "阿联酋", "泰国" }, { "智利", "波多黎各", "南非", "韩国", "墨西哥", "土耳其", "埃及", "委内瑞拉", "玻利维亚", "乌克兰" }, { "以色列", "海地", "中国", "沙特阿拉伯", "俄罗斯", "哥伦比亚", "尼日利亚", "巴基斯坦", "伊朗", "伊拉克" } };

	private Handler handler;
	/** 总页数. */
	private int PageCount;
	/** 当前页码. */
	private int PageCurrent;
	/** 被选中的. */
	private int gridID = -1;
	/** 每页显示的数量，Adapter保持一致. */
	private static final float PAGE_SIZE = 12.0f;
	/** GridView. */
	private GridView gridView;
	/** 自定义的左右滑动. */
	private ViewPager vp;
	/** 页码条布局. */
	private LinearLayout layoutBottom;

	/** 页码条. */
	private ImageView imgCur;
	// common private
	// private PullDownView commonView;
	private ListView commonLv;
	private PullDownView privateView;
	private ListView privateLv;
	// private PullDownView otherView;
	// private ListView otherLv;

	private List<View> list;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.activity_comment, container, false);

		initViews(view);
		phone = UserPreferences.getInstance(getActivity()).getCurrentUser().getPhone();
		setGrid();
		return view;
		//

	}

	/**
	 * 初始化
	 */
	private TextView commonText;
	private TextView privateText;
	private View commonTab;
	private View privateTab;

	// private TextView otherText;
	// private View otherTab;

	private void initViews(View view) {
		((ImageView) view.findViewById(R.id.backImageButton)).setVisibility(View.INVISIBLE);
		ImageView next = (ImageView) view.findViewById(R.id.nextImageButton);
		next.setImageResource(R.drawable.common_write_switcher);
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// startForResult 
				getActivity().startActivityForResult(new Intent(getActivity(), com.dynamic.WriteActivity.class), RequestCode.NOCARE);

			}
		});
		ImageView pen = (ImageView) view.findViewById(R.id.pen);

		pen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// startForResult 
				getActivity().startActivityForResult(new Intent(getActivity(), com.dynamic.WriteActivity.class), RequestCode.NOCARE);

			}
		});
		((TextView) view.findViewById(R.id.title)).setText("热评");
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// /-----------init data

		// // init data finished
		list = new ArrayList<View>();
		ImageView homeButton = ((ImageView) view.findViewById(R.id.backImageButton));
		homeButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//MainActivity.moveToSpecifiedTab(getApplicationContext(), 0);
			}
		});
		// 设置tab 变化。
		vp = (ViewPager) view.findViewById(R.id.vp_message_launcher_layout);
		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				setCurPage(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
		commonText = (TextView) view.findViewById(R.id.commonText);
		commonText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (vp.getCurrentItem() != 0) {

					vp.setCurrentItem(0);
					System.out.println(vp.getCurrentItem());
				}
			}
		});
		privateText = (TextView) view.findViewById(R.id.privateText);
		privateText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (vp.getCurrentItem() != 1) {

					vp.setCurrentItem(1);
				}
			}
		});
		// otherText = (TextView) findViewById(R.id.otherText);
		// otherText.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if (vp.getCurrentItem() != 2) {
		//
		// vp.setCurrentItem(2);
		// }
		// }
		// });
		commonTab = view.findViewById(R.id.commonTab);
		privateTab = view.findViewById(R.id.privateTab);
		// otherTab = findViewById(R.id.otherTab);

		layoutBottom = (LinearLayout) view.findViewById(R.id.layout_scr_bottom);

	}

	/**
	 * 添加ListView
	 * 
	 */
	private ZrcListView[] listViews;
	private ViewGroup[] waitViewGroups;
	private View[] containers;;
	private MessageAdapter[] messageAdapters;
	private List<Map<String, String>>[] datas;
	private LayoutInflater mInflater;
	private int[] currentPage = { 1, 1 }; // 当前加载页数

	// **设置listview 头部底部的样式
	private void setStyle(ZrcListView listView) {
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(getActivity());
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		listView.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(getActivity());
		footer.setCircleColor(0xff33bbee);
		listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		listView.setItemAnimForTopIn(R.anim.topitem_in);
		listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 开启 加载更多多 的功能
		listView.startLoadMore();
	}

	private TextView tv;

	private void setGrid() {
		// 初始化数据
		listViews = new ZrcListView[2];
		waitViewGroups = new ViewGroup[2];
		containers = new View[2];
		messageAdapters = new MessageAdapter[2];
		datas = new List[2];
		// 在这里添加视图。多个自定义的View
		mInflater = LayoutInflater.from(getActivity());
		for (int i = 0; i < 2; i++) {
			waitViewGroups[i] = (ViewGroup) mInflater.inflate(R.layout.fragment_wait, null);
			containers[i] = mInflater.inflate(R.layout.component_comment_mylistview, null);
			listViews[i] = (ZrcListView) containers[i].findViewById(R.id.zListView);
			listViews[i].setDivider(getResources().getDrawable(R.color.common_list_devider_color));
			listViews[i].setDividerHeight(2);

			setStyle(listViews[i]);
			datas[i] = new ArrayList<Map<String, String>>();
			messageAdapters[i] = new MessageAdapter(getActivity(), i, datas[i]);
		}
		tv = (TextView) waitViewGroups[0].findViewById(R.id.tv);
		if (phone != null) {
			callMyCommentsNetwork();
		} else {
			SimpleToast.info(getActivity(), "登陆先");
			waitViewGroups[0].findViewById(R.id.circle).setVisibility(View.INVISIBLE);//隐藏
			tv.setVisibility(View.VISIBLE);
			tv.setText("点击登录");

			tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// 没有登录。 此处不能用cas，直接 调用登陆界面
					Intent intent = new Intent(getActivity(), LoginActivity.class);
					intent.putExtra("relogin", false);
					getActivity().startActivityForResult(intent, RequestCode.MyComment);
					//直接startActivityForResult(intent, RequestCode.MyComment) 会有问题。RequestCode会改变
				}
			});

		}

		//callNetwork();

		String urlString1 = "comment/list?current=1&count=" + COUNT;
		HttpUtil.get(urlString1, new DownloadCommentHandler(listViews[1], waitViewGroups[1], messageAdapters[1], 1, false));

		for (int i = 0; i < 2; i++) {
			final int index = i;
			// 下拉刷新事件回调（可选）
			listViews[index].setOnRefreshStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					refresh(index);
				}
			});

			// 加载更多事件回调（可选）
			listViews[index].setOnLoadMoreStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					loadMore(index);
				}
			});

		}

		for (ViewGroup temp : waitViewGroups) {
			list.add(temp);
		}
		vp.setAdapter(new MyAdapter());

	}

	private void refresh(int index) {

		String urlString = "comment/list?current=1&count=" + COUNT;
		datas[index] = new ArrayList<Map<String, String>>();

		switch (index) {
		case 0:
			urlString = "comment/minelist?phone=" + phone + "&current=1&count=" + COUNT;
			break;
		case 1:
			urlString = "comment/list?current=1&count=" + COUNT;
			break;

		default:

			break;
		}
		HttpUtil.get(urlString, new DownloadCommentHandler(listViews[index], waitViewGroups[index], messageAdapters[index], index, true));

		// adapter.notifyDataSetChanged();
		// listView1.setRefreshSuccess("加载成功"); // 通知加载成功
		// listView1.startLoadMore(); // 开启LoadingMore功能

	}

	private void loadMore(int index) {
		currentPage[index] = currentPage[index] + 1;

		String urlString = "comment/minelist?phone=" + phone + "&current=" + currentPage[index] + "&count=" + COUNT;

		switch (index) {
		case 0:
			urlString = "comment/minelist?phone=" + phone + "&current=" + currentPage[index] + "&count=" + COUNT;
			break;
		case 1:
			urlString = "comment/list?current=" + currentPage[index] + "&count=" + COUNT;
			break;

		default:

			break;
		}

		HttpUtil.get(urlString, new DownloadMoreCommentHandler(listViews[index], waitViewGroups[index], messageAdapters[index], datas[index], index));

	}

	class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(list.get(arg1));
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(list.get(arg1));
			return list.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

		@Override
		public void finishUpdate(View arg0) {
		}

	}

	/**
	 * 更新当前页码
	 */
	public void setCurPage(int page) {
		switch (page) {
		case 0:
			commonText.setTextColor(0xffFFD101);
			privateText.setTextColor(0xffcccccc);
			// otherText.setTextColor(0xffcccccc);
			commonTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			// otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		case 1:
			privateText.setTextColor(0xffFFD101);
			commonText.setTextColor(0xffcccccc);
			// otherText.setTextColor(0xffcccccc);
			privateTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			// otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		// case 2:
		// otherText.setTextColor(0xff000000);
		// commonText.setTextColor(0xffcccccc);
		// privateText.setTextColor(0xffcccccc);
		// otherTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
		// commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
		// privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
		// break;
		default:
			break;
		}
	}

	// 异步下载信息

	private SimpleDateFormat sdf;

	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View

	public class MessageAdapter extends BaseAdapter {
		private List<Map<String, String>> data;
		private int messageType;

		public MessageAdapter(Context context, int messageType, List<Map<String, String>> data) {
			this.mInflater = LayoutInflater.from(context);
			this.data = data;
			this.messageType = messageType;
		}

		// ViewHolder静态类
		private LayoutInflater mInflater = null;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Map<String, String> map = this.data.get(position);

			holder = null;

			//int type = getItemViewType(position);
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.item_ninegridlayout, parent, false);

				holder.ivMore = (NineGridlayout) convertView.findViewById(R.id.iv_ngrid_layout);
				holder.ivOne = (CustomImageView) convertView.findViewById(R.id.iv_oneimage);
				holder.wordText = (TextView) convertView.findViewById(R.id.text);
				holder.timeText = (TextView) convertView.findViewById(R.id.time);
				holder.nameText = (TextView) convertView.findViewById(R.id.name);
				holder.thumbView = (ImageView) convertView.findViewById(R.id.thumbImage);
				holder.replyView = (ImageView) convertView.findViewById(R.id.replyIcon);
				holder.openORclose = (TextView) convertView.findViewById(R.id.openORclose);
				holder.expandView = (ExpandView) convertView.findViewById(R.id.expandView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			//			List<Image> itemList = new ArrayList<Image>();
			//			String[] images = map.get("IMAGES").split(";");
			//			for (String str : images) {
			//				
			//				 String[] info = str.split("_");
			//				itemList.add(new Image(baseImageURL + info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2])));
			//			}
			List<Image> itemList = new ArrayList<Image>();
			String[] images = map.get(IMAGE).split(";");
			for (String str : images) {

				String[] info = str.split("_");
				itemList.add(new Image(baseImageURL + info[0] + "?p=0", Integer.parseInt(info[1]), Integer.parseInt(info[2])));
			}
			// 设置监听器。
			ItemClickListener icl = new ItemClickListener(map.get(IMAGE));
			if (itemList.size() == 0) {
				holder.ivMore.setVisibility(View.GONE);
				holder.ivOne.setVisibility(View.GONE);
			} else if (itemList.size() == 1) {
				holder.ivMore.setVisibility(View.GONE);
				holder.ivOne.setVisibility(View.VISIBLE);
				holder.ivOne.setOnClickListener(icl);

				handlerOneImage(holder, itemList.get(0));
			} else {
				holder.ivMore.setVisibility(View.VISIBLE);
				holder.ivOne.setVisibility(View.GONE);
				holder.ivMore.setImagesData(map.get(IMAGE), itemList);
				//				holder.ivMore.setOnClickListener(icl);// 这句话不用了
			}

			//			holder.moneyText.setText(map.get(MONEY));
			//			holder.dateText.setText(map.get(DATE));
			//			holder.timeText.setText(map.get(TIME));
			//			holder.uuidText.setText(map.get(UUID));
			holder.wordText.setText(map.get(WORD));
			holder.timeText.setText(map.get(TIME));
			holder.nameText.setText(map.get(USERNAME));
			if (map.get(THUMB) != null) {
				imageLoader.displayImage(map.get(THUMB), holder.thumbView, squareOptions, animateFirstListener);
			}
			// 不设置这个，点击背景会变色。 
			convertView.setOnLongClickListener(new ViewClickListener(map));

			// 点击收缩。

			//holder.openORclose.setOnClickListener(new ExpandClickListener(holder.expandView, map.get(CID)));
			if (StringUtils.isEmpty(map.get(REPLYS))) {
				holder.openORclose.setText("回复(0)");
			} else {
				int num = map.get(REPLYS).split(";").length;
				holder.openORclose.setText("回复(" + num + ")");
			}
			// 点击回复
			holder.replyView.setOnClickListener(new ReplyClickListener(map.get(CID)));
			return convertView;
		}

		@Override
		public int getCount() {
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		private void handlerOneImage(ViewHolder viewHolder, Image image) {
			int totalWidth;
			int imageWidth;
			int imageHeight;
			ScreenTools screentools = ScreenTools.instance(getActivity());
			totalWidth = screentools.getScreenWidth() - screentools.dip2px(80);
			imageWidth = screentools.dip2px(image.getWidth());
			imageHeight = screentools.dip2px(image.getHeight());
			if (image.getWidth() <= image.getHeight()) {
				if (imageHeight > totalWidth) {
					imageHeight = totalWidth;
					imageWidth = (imageHeight * image.getWidth()) / image.getHeight();
				}
			} else {
				if (imageWidth > totalWidth) {
					imageWidth = totalWidth;
					imageHeight = (imageWidth * image.getHeight()) / image.getWidth();
				}
			}
			ViewGroup.LayoutParams layoutparams = viewHolder.ivOne.getLayoutParams();
			layoutparams.height = imageHeight;
			layoutparams.width = imageWidth;
			viewHolder.ivOne.setLayoutParams(layoutparams);
			viewHolder.ivOne.setClickable(true);
			viewHolder.ivOne.setScaleType(android.widget.ImageView.ScaleType.CENTER_CROP);
			//imageLoader.displayImage(image.getUrl(), viewHolder.ivOne, squareOptions, animateFirstListener);
			viewHolder.ivOne.setImageUrl(image.getUrl());

		}

	}

	class ViewClickListener implements OnLongClickListener {
		private Map<String, String> map;

		public ViewClickListener(Map<String, String> map) {
			this.map = map;
		}

		@Override
		public boolean onLongClick(View arg0) {
			Intent intent = new Intent(getActivity(), CommentDetailsActivity.class);
			intent.putExtra(CID, map.get(CID));
			intent.putExtra(ID, map.get(ID));
			intent.putExtra(IMAGE, map.get(IMAGE));
			intent.putExtra(WORD, map.get(WORD));
			intent.putExtra(USERNAME, map.get(USERNAME));
			intent.putExtra(REPLYS, map.get(REPLYS));
			intent.putExtra(TIME, map.get(TIME));
			intent.putExtra(THUMB, map.get(THUMB));

			startActivity(intent);
			return false;
		}

	}

	class ExpandClickListener implements OnClickListener {
		private ExpandView mExpandView;
		private String cid;

		public ExpandClickListener(ExpandView mExpandView, String cid) {
			this.mExpandView = mExpandView;
			this.cid = cid;
		}

		@Override
		public void onClick(View arg0) {
			if (mExpandView.isExpand()) {
				mExpandView.collapse();
			} else {
				//  http 请求， 然后就是 setContent，展开。
				String url = "comment/getReplys?commentId=" + cid;

				HttpUtil.get(url, new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						try {
							JavaType type1 = getObjectMapper().getTypeFactory().constructCollectionType(List.class, CommentReply.class);
							JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, type1);
							ResponseResult result = getObjectMapper().readValue(arg2, javaType);
							mExpandView.setContentView(baseImageURL, imageLoader, (List<CommentReply>) result.getObject());
							mExpandView.expand();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						String e = "";
					}
				});

			}
		}

	}

	class ItemClickListener implements OnClickListener {
		private String images;

		public ItemClickListener(String images) {
			this.images = images;
		}

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(getActivity(), ViewPagerExampleActivity.class);
			intent.putExtra("images", images);
			startActivity(intent);
		}

	}

	class ReplyClickListener implements OnClickListener {
		private String cid;

		public ReplyClickListener(String cid) {
			this.cid = cid;
		}

		@Override
		public void onClick(View arg0) {

			LayoutInflater inflater1 = LayoutInflater.from(getActivity());
			final View namepicker1 = inflater1.inflate(R.layout.component_comment_reply, null);
			final EditText replyEdit = (EditText) namepicker1.findViewById(R.id.word);
			final MyAlertDialog dialog = new MyAlertDialog(getActivity()).builder().setTitle("回复").setView(namepicker1).setNegativeButton("取消", new OnClickListener() {
				@Override
				public void onClick(View v) {
				}
			});

			dialog.setPositiveButton("提交", new OnClickListener() {
				@Override
				public void onClick(View v) {
					globalCid = cid;
					globalWord = replyEdit.getText().toString();
					if (StringUtils.isEmpty(replyEdit.getText().toString())) {
						SimpleToast.info(getActivity(), "回复不能为空");
						return;
					}
					if (globalWord.length() > 200) {
						SimpleToast.info(getActivity(), "文字不能超过200");
						return;
					}

					CAS call = new CAS(getActivity(), RequestCode.MyReply, new CallBack() {
						@Override
						public void method() {
							postreply();
						}
					});
					call.call();
				}
			});
			dialog.show(true);

		}
	}

	private String globalCid;
	private String globalWord;

	protected void postreply() {
		String url = "comment/reply";
		RequestParams rp = new RequestParams();
		rp.add("commentId", globalCid);
		rp.add("word", globalWord);

		HttpUtil.post(url, rp, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

				SimpleToast.info(getActivity(), "回复成功");
				// 刷新 列表
				refresh(0);
				refresh(1);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				SimpleToast.info(getActivity(), "回复失败,原因：");
			}
		});
	}

	static class ViewHolder {
		public TextView wordText;
		public TextView timeText;
		public TextView nameText;
		public TextView openORclose;
		public ExpandView expandView;
		public ImageView thumbView;
		public ImageView replyView;
		public NineGridlayout ivMore;
		public CustomImageView ivOne;

	}

	private class MyAdapter2 extends BaseAdapter {
		@Override
		public int getCount() {
			return msgs == null ? 0 : msgs.size();
		}

		@Override
		public Object getItem(int position) {
			return msgs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textView;
			if (convertView == null) {
				textView = (TextView) getActivity().getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
			} else {
				textView = (TextView) convertView;
			}
			textView.setText(msgs.get(position));
			return textView;
		}
	}

	// / 写一个通用的类。
	class DownloadCommentHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		// private List<Map<String, String>> data;
		private int index;
		private boolean isRefresh;

		public DownloadCommentHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, int index, boolean isRefresh) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			// this.data = data;
			this.index = index;
			this.messageAdapter = messageAdapter;
			this.isRefresh = isRefresh;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			listView.setRefreshSuccess("加载失败");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				System.out.println(new String(responseStr));
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, CommentRecords.class);
				ResponseResult<CommentRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloadData = new ArrayList<Map<String, String>>();
				//设置 data
				downloadData = setData(index, result);

				// 设置data ends

				datas[index].addAll(downloadData);
				if (!isRefresh) {

					listView.setAdapter(messageAdapter);
					// listView.refresh(); // 主动下拉刷新
					waitViewGroup.removeAllViews();
					waitViewGroup.addView(containers[index]);

				} else {
					// 刷新

					messageAdapter.data = datas[index];
					messageAdapter.notifyDataSetChanged();
					listView.setRefreshSuccess("加载成功"); // 通知加载成功
					// 开启 加载更多多 的功能
					//listView.startLoadMore();
				}
				if (index == 0) {// 去掉 提示窗口
					tv.setVisibility(View.GONE);
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	// / 写一个通用的类。
	class DownloadMoreCommentHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		private List<Map<String, String>> data;
		private int index;

		public DownloadMoreCommentHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, List<Map<String, String>> data, int index) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			this.data = data;
			this.messageAdapter = messageAdapter;
			this.index = index;

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			AgainPlayer.makeCall(getActivity(), "网络异常");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, CommentRecords.class);
				ResponseResult<CommentRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloaddata = new ArrayList<Map<String, String>>();
				//设置 data
				downloaddata = setData(index, result);

				if (downloaddata.size() == 0) {
					listView.stopLoadMore();
				} else {
					data.addAll(downloaddata);
					messageAdapter.notifyDataSetChanged();
					listView.setLoadMoreSuccess(); // 通知加载成功
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private List<Map<String, String>> setData(int index, ResponseResult<CommentRecords> result) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (Comment comment : result.getObject().getRecordList()) {
			Map<String, String> map = new HashMap<String, String>();
			// 计算时间 。。几分钟前，几小时前。等等
			map.put(TIME, RelativeDateFormat.format(comment.getPostTime()));
			map.put(IMAGE, comment.getImages());
			map.put(WORD, comment.getWord());
			map.put(ID, comment.getUser_id());
			map.put(REPLYS, comment.getReplyIds());
			map.put(USERNAME, comment.getUserName());
			map.put(CID, comment.getId() + "");
			if (!StringUtils.isEmpty(comment.getUser_image())) {
				map.put(THUMB, baseImageURL + comment.getUser_image() + "?p=0");
			} else {
				map.put(THUMB, null);
			}
			list.add(map);
		}
		return list;

	}

	public void callMyCommentsNetwork() { // 会被回调
		phone = UserPreferences.getInstance(getActivity()).getCurrentUser().getPhone();
		if (phone != null) {
			String urlString0 = "comment/minelist?phone=" + phone + "&current=1&count=" + COUNT;
			HttpUtil.get(urlString0, new DownloadCommentHandler(listViews[0], waitViewGroups[0], messageAdapters[0], 0, false));
		}
	}

	public void refreshMyCommentsNetwork() { // 会被回调
		refresh(0);
		refresh(1);
	}

}